import {
  getImage,
  getPage,
  getTabbar
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  storage,
  promisify,
  $toast,
  $loading,
  $query
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import {
  headerInfo
} from '../../utils/env'
const app = getApp();
let topStyle, leftStyle, tipTopStyle;

{
  let {
    height,
    right,
    menuWidth
  } = headerInfo
  //console.log(headerInfo)
  leftStyle = `right: ${((menuWidth / 2) / 2) + right}px`;
  tipTopStyle = `top: ${height}px;`;
  topStyle = `top: ${height + 10}px;`;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getImage: getImage,
    getPage: getPage,
    logged: 0,
    loading: 0,
    userId: 0,
    navbar: {},
    window: {},
    city: "",
    goodsList: [],
    goodsListPage: 1,
    goodsListPages: 0,
    loadmore: true,
    loaddone: false,
    rec_list: [],
    rec_pageindex: 1,
    rec_pages: 0,
    rec_loadmore: true,
    rec_loaddone: false,
    tipTopStyle: tipTopStyle,
    leftStyle: leftStyle,
    topStyle: topStyle,
    value1: 0,
    abnor: false,
    cid: 0,
    imgheightsUser: {},
  },

  mesClick(e) {
    wxApi.navigateTo("/pages/location/index");
  },

  /**
   * 搜索
   */
  visitSearch() {
    wxApi.navigateTo(getPage.searchfabu);
  },

  golink(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    //console.log(data.url);
    //转为小写并去除左右空格
    var str = data.url.toLowerCase();
    if (str != "") {
      if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
        wxApi.navigateTo("/pages/web/web?id=" + str);
      } else if (str.indexOf('za://') == 0) {
        //console.log(str);
        var array = str.split('_');
        //console.log(array);
        if (array[0].replace("za://", "") == 'column') {
          app.g_cid = array[1];
          wx.switchTab({
            url: getPage.column
          });
        }
      } else {
        wxApi.navigateTo("/pages/goods/goods?id=" + str);
      }
    }
  },
  /**
   * 禁止手动滑动
   */
  noSwiping() {
    return false;
  },

  /**
   * 获取产品数据
   */
  getProductsInfo(cb, a = false) {
    let {
      goodsNavType,
      goodsListPage,
      goodsListPages,
      cid,
      loaddone,
      abnor,
      userId
    } = this.data;
    var latitude = 0,
      longitude = 0;
    var mylocation = null;
    if (wx.getStorageSync('mylocation') == "" && app.globalData.zone == null) {
      wxApi.navigateTo("/pages/location/index");
      return;
    } else if (wx.getStorageSync('mylocation') != "") {
      mylocation = JSON.parse(wx.getStorageSync('mylocation'));
      latitude = mylocation.latitude;
      longitude = mylocation.longitude;
    } else {
      latitude = app.globalData.zone.lat;
      longitude = app.globalData.zone.lng;
    }
    http.post(api.default, {
      data: {
        action: 'getxuqiulist',
        userid:userId,
        pagesize: 20,
        pageindex: goodsListPage,
        cid: cid,
        latitude: latitude,
        longitude: longitude,
        keyword: this.data.keyword
      }
    }, a).then((res) => {
      const {
        data
      } = res.data;
      //是否加载完毕
      if (data.pages == 0)
      abnor = true;
      else
      abnor = false;
      if (goodsListPage == data.pages && !abnor) loaddone = true;
      else loaddone = false;
      this.setData({
        goodsListPages: data.pages,
        loaddone,
        abnor,
        loading: 1
      });
      cb && cb(data);
    });
  },
  goHome() {
    //存在上一页,关闭当前返回一层,//没有上一页，跳回首页
    this.data.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.xqlist);
  },

  goxuqiudetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    if (data.id) {
      wxApi.navigateTo(getPage.xuqiudetail, {
        id: data.id
      });
    }
  },

  imageLoadUser: function (e) { //获取图片真实宽度 
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    let bol = ratio>1? true :false
    var imgheightsUser = this.data.imgheightsUser;
    imgheightsUser[e.target.dataset.id] = bol;
    this.setData({
      imgheightsUser: imgheightsUser
    })
  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //判断入口是否带参数
    if (options && JSON.stringify(options) !== '{}') {
      this.setData({
        keyword: options.keyword
      });
    }
    /**
     * 获取用户信息 
     */
    let logged, userId = '';
    app.getLogin().then((res) => {
      logged = res.code;
      userId = res.data.user.user_id;
    }).catch((res) => {
      logged = res;
    }).finally(() => {
      this.setData({
        logged,
        userId
      });
    })
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(options) {

    app.getLogin().then(res => {
      const {
        user
      } = res.data;
      this.setData({
        userId: user.user_id
      });
      //加载产品列表
      this.getProductsInfo((res) => {
        console.log(res)
        this.setData({
          goodsList: res.list,
          loadmore: false,
        });
        console.log('goodsList==',this.data.goodsList)
      });
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let {
      goodsListPage,
      goodsListPages,
      loadmore
    } = this.data;
    //未请求完且未在加载中
    if (goodsListPages > goodsListPage && !loadmore) {
      goodsListPage++;
      loadmore = true;

      //显示加载效果
      this.setData({
        goodsListPage,
        loadmore
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.getProductsInfo((res) => {
        let {
          goodsList
        } = this.data;
        loadmore = false;
        this.setData({
          loadmore,
          goodsList: goodsList.concat(res.list),
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.userId > 0) {
      pageshare += "?pid=" + this.data.userId;
    }
    return {
      title: ``,
      imageUrl: '',
      path: pageshare,
      success: function (res) {
        //console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          //console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          //console.log("分享失败");
        }
      }
    }
  }
})